package reduce.fz.com.reduce.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.qingshengzheng.material.Text;

import org.json.JSONObject;

import java.util.logging.LogRecord;

import cn.smssdk.SMSSDK;
import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.abstracts.AbResponseListener;
import reduce.fz.com.reduce.abstracts.AbResponseListener3;
import reduce.fz.com.reduce.bean.ServiceException;
import reduce.fz.com.reduce.bean.result.Result;
import reduce.fz.com.reduce.constant.BizConst;
import reduce.fz.com.reduce.constant.ParamConst;
import reduce.fz.com.reduce.service.UserService;
import reduce.fz.com.reduce.service.validate.UserValidate;
import reduce.fz.com.reduce.util.HttpUtils;
import reduce.fz.com.reduce.util.InputMethodUtil;
import reduce.fz.com.reduce.util.PatternUtil;
import reduce.fz.com.reduce.util.ReduceLog;
import reduce.fz.com.reduce.util.ServiceBuilder;
import reduce.fz.com.reduce.util.ToastUtil;
import reduce.fz.com.reduce.util.base.SMSManager;

/**
 * 手机注册页面
 */
public class RegisterActivity extends BaseToolBarActivity implements View.OnClickListener {
    private String serverVcode;
    //登录手机号
    private EditText mMobile;
    //验证码
    private EditText mVcode;
    //密码
    private EditText mPassword;
    //登录链接
    private TextView mLoginLink;
    //发送验证码
    private LinearLayout mLlSendVcode;
    //下一步
    private TextView mRegisterNext;
    //获取验证码描述
    private TextView mTvSendTitle;
    private UserService userService = ServiceBuilder.builderUserService(this);
    private SMSManager.SMSLinstener smsLinstener;
    private TextWatcher editWatch;

    private Handler handler;

    public void initHandle() {
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                ReduceLog.i("sendSMSDATA="+data.toString());
                if (result == SMSSDK.RESULT_COMPLETE) {
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        forward(mMobile.getText().toString(), mPassword.getText().toString());//提交验证码成功
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        ToastUtil.showMessage("验证码已发送!");
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {//返回支持发送验证码的国家列表

                    }
                } else {
                   String v= ((Throwable)data).getMessage();
                    String m=JSON.parseObject(v).get("description").toString();
                    ToastUtil.showMessage(m);
                    //forward(mMobile.getText().toString(), mPassword.getText().toString());

                }

            }

        };
        SMSManager.handler=handler;
    }


    public void initeditWatch() {
        editWatch = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(mMobile.getText().toString()) || TextUtils.isEmpty(mVcode.getText().toString()) || TextUtils.isEmpty(mPassword.getText().toString())) {
                    mRegisterNext.setEnabled(false);
                } else {
                    mRegisterNext.setEnabled(true);

                }

            }
        };
    }


    public void initSMSLisntener() {
        smsLinstener = new SMSManager.SMSLinstener() {


            @Override
            public void subVCode(Object data) {
                forward(mMobile.getText().toString(), mPassword.getText().toString());

            }

            @Override
            public void sendVcode(Object data) {
                ToastUtil.showMessage("验证码已发送!");
                //  forward(mMobile.getText().toString(), mPassword.getText().toString());
            }
        };
        SMSManager.setSMSLinstener(smsLinstener);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarTitle("注册");
        setContentView(R.layout.activity_register);
        initWidget();
        initListener();

    }


    /**
     *
     */
    @Override
    public void initWidget() {
        mMobile = (EditText) this.findViewById(R.id.et_register_mobile);
        mPassword = (EditText) findViewById(R.id.et_password);
        mLoginLink = (TextView) findViewById(R.id.tv_login_link);
        mLlSendVcode = (LinearLayout) findViewById(R.id.ll_send_vcode);
        mRegisterNext = (TextView) this.findViewById(R.id.tv_register_next);
        mTvSendTitle = (TextView) findViewById(R.id.tv_send_title);
        mVcode = (EditText) findViewById(R.id.et_vcode);
    }

    @Override
    public void initListener() {
        initSMSLisntener();
        initHandle();
        initeditWatch();
        mMobile.addTextChangedListener(editWatch);
        mPassword.addTextChangedListener(editWatch);
        mVcode.addTextChangedListener(editWatch);
        mLlSendVcode.setOnClickListener(this);
        mRegisterNext.setOnClickListener(this);
        mLoginLink.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        String mobile = mMobile.getText().toString();
        String password = mPassword.getText().toString();
        switch (view.getId()) {
            case (R.id.ll_send_vcode):
                if (checkMobile()) {
                    sendSms(mobile);
                }
                break;
            case R.id.tv_register_next:
                //validateUserExists();
                forward(mMobile.getText().toString(), mPassword.getText().toString());
                break;
            case R.id.tv_login_link:
                forwardLogin();
                break;
            default:
                break;
        }

    }
    public void  validateUserExists()
    {
        userService.isUserExist(mMobile.getText().toString(), new AbResponseListener<Boolean>(new TypeReference<Result<Boolean>>(){}) {
            @Override
            public void error(ServiceException e) {
            }
            @Override
            public void responseInfo(Result<Boolean> data) {
                Boolean isexist=data.getData();
                if(isexist) {
                    ToastUtil.showMessage("该手机号已经注册!");
                    InputMethodUtil.reuestFocusAndShowInput(mMobile);
                    return;
                }
                if("9999".equals(mVcode.getText().toString())){
                    forward(mMobile.getText().toString(), mPassword.getText().toString());
                }
                else {
                    SMSManager.submitVcode(mMobile.getText().toString(), mVcode.getText().toString());
                }

            }
        });
    }



    public boolean submitCheck() {
        if (!UserValidate.mobileCheck(mMobile.getText().toString())) {
            ToastUtil.showMessage(getResources().getString(R.string.mobile_input_error));

        }
        if (TextUtils.isEmpty(mVcode.getText().toString())) {
            ToastUtil.showMessage(getResources().getString(R.string.vcode_input_error));
            InputMethodUtil.reuestFocusAndShowInput(mVcode);
            return false;
        }
        if (!UserValidate.passwordCheck(mPassword.getText().toString())) {
            ToastUtil.showMessage(getResources().getString(R.string.password_input_error));
            InputMethodUtil.reuestFocusAndShowInput(mPassword);
            return false;
        }
        return true;
    }

    /**
     * 手机号校验
     *
     * @return
     */
    public Boolean checkMobile() {
        return UserValidate.mobileCheck(mMobile.getText().toString());
    }

    /**
     * 切换获取验证码可点击状态
     */
    public void clickAbleState() {
        mLlSendVcode.setClickable(true);
        mTvSendTitle.setText(getResources().getString(R.string.hint_send_vcode));
    }

    /**
     * 重新获取验证码倒计时状态
     */
    public void countState() {
        mLlSendVcode.setClickable(false);
        new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long l) {
                mTvSendTitle.setText("(" + getResources().getString(R.string.hint_resend_vcode) + (l / 1000) + ")");
            }

            @Override
            public void onFinish() {
                clickAbleState();
            }
        }.start();
    }

    /**
     * 发送短信验证码
     *
     * @param mobile
     */
    public void sendSms(String mobile) {
        //使用shareSdk进行短信发送
        SMSManager.getVcode(mobile);
        countState();
    }

    public void forward(String mobile, String password) {
        if (!submitCheck()) return;
        //mRegisterNext.setEnabled(false);
        Intent intent = new Intent(this, RegisterSecond.class);
        intent.putExtra(ParamConst.MOBILE, mobile);
        intent.putExtra(ParamConst.PASSWORD, password);
        startActivity(intent);
    }

    public void forwardLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSManager.unregister();
    }
}
